/* Copyright 2011 Tobias Marschall, Email: tm@cwi.nl 
 * 
 * This file is part of string-cover.
 *
 * string-cover is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * string-cover is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with string-cover.  If not, see <http://www.gnu.org/licenses/>.
 */

#include <assert.h>
#include "StringFactorization.h"

using namespace std;

StringFactorization::StringFactorization(size_t string_length) : bitarray(string_length-1) {
}

StringFactorization::StringFactorization(const boost::dynamic_bitset<>& bitarray) : bitarray(bitarray) {
}

StringFactorization::~StringFactorization() {
}

StringFactorization::StringFactorization(size_t string_length, unsigned long  start_value) : bitarray(string_length-1, start_value) {
}

size_t StringFactorization::size() const {
	return bitarray.size() + 1;
}

void StringFactorization::addBreakpoint(size_t position) {
	assert(position < bitarray.size());
	bitarray.set(position, true);
}

string StringFactorization::printFactorizedString(string s) const {
	assert(s.length()-1 == bitarray.size());
	string result;
	for (size_t i=0; i<s.length(); ++i) {
		result += s[i];
		if ((i<bitarray.size()) && bitarray[i]) result += '|';
	}
	return result;
}

auto_ptr<vector<StringFactorization::interval_t> > StringFactorization::getIntervals() const {
	auto_ptr<vector<interval_t> > result(new vector<interval_t>());
	size_t start = 0;
	for (size_t p=bitarray.find_first(); p!=bitarray.npos; p=bitarray.find_next(p)) {
		result->push_back(make_pair(start,p+1));
		start = p+1;
	}
	result->push_back(make_pair(start,bitarray.size()+1));
	return result;
}

bool StringFactorization::operator==(const StringFactorization& st) const {
	return bitarray == st.bitarray;
}

class XorFunction {
private:
	size_t* value;
public:
	XorFunction(size_t* value) : value(value){}
    void operator()(const size_t& x) const {
        *value ^= x;
    }
};

const boost::dynamic_bitset<> & StringFactorization::getBreakpoints() const {
	return bitarray;
}

void StringFactorization::addAllBreakpoints() {
	bitarray.set();
}

/** Function allowing to use boost::dynamic_bitset as key in hash sets and maps. */
std::size_t boost::hash_value(const StringFactorization& st) {
	size_t result = 0;
    boost::to_block_range(st.bitarray, make_function_output_iterator(XorFunction(&result)));
    return result ^ st.bitarray.size();
}
